<template>
  <div class="cache-rule" :style="{ '--width': `${width}px` }">
    <div class="cache-rule__top">
      <div class="flex-1 label">文件后缀</div>
      <div class="label w-50">缓存时间</div>
      <div class="label w-15">操作</div>
    </div>
    <div class="cache-rule__body" :style="rowHeightStyle">
      <a-form
        ref="formRefs"
        :model="item"
        :rules="rules"
        layout="vertical"
        v-for="(item, index) in list"
        :key="index"
        scroll-to-first-error
        class="rule-list">
        <div class="flex-1 box-border item">
          <a-form-item field="suffix" hide-asterisk required>
            <a-input
              v-model.trim="item.suffix"
              placeholder="请输入文件后缀，多个值用英文逗号隔开，区分大小写"
              :max-length="256" />
          </a-form-item>
        </div>
        <div class="w-50 text-2 cloud-diverse-select !h-unset item">
          <a-form-item
            field="cache_time"
            hide-asterisk
            :rules="{ required: true, message: '请输入缓存时间' }"
            validate-trigger="blur"
            required>
            <a-input-number
              v-model="item.cache_time"
              :min="1"
              :max="item.cache_unit === 'd' ? 365 : 99999"
              :controls="false"
              :step="1"
              :precision="0"
              placeholder="请输入"
              class="flex-1">
              <template #append>
                <a-select
                  v-model="item.cache_unit"
                  class="!w-78px"
                  :options="cacheTimeOptions">
                </a-select>
              </template>
            </a-input-number>
          </a-form-item>
        </div>
        <div class="w-15 leading-8 item">
          <a-link
            status="danger"
            :hoverable="false"
            :disabled="list.length <= 1"
            class="!h-8 inline-block"
            @click="handleDelete(index)">
            删除
          </a-link>
        </div>
      </a-form>
    </div>
    <div class="cache-rule__footer">
      <section
        @click="append"
        class="flex items-center gap-x-6px select-none"
        :class="{ 'disable-btn': isDisable }">
        <i-icons-table-add />
        新增规则
      </section>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { FieldRule, FormInstance } from '@arco-design/web-vue'

interface IProps {
  validate?: boolean
  maxDisplayRows?: number
  width?: number
}

const props = withDefaults(defineProps<IProps>(), {
  validate: true,
  maxDisplayRows: 5,
  width: 960
})
const formRefs = ref<FormInstance[]>()
const rules = computed<Record<string, FieldRule[]>>(() => {
  const res: Record<string, FieldRule[]> = {
    suffix: [
      { required: true, message: '请输入文件后缀' },
      {
        validator: validateSuffix
      }
    ]
  }
  return res
})

/** 自定义行高 */
const rowHeightStyle = computed(() => {
  return {
    maxHeight: props.maxDisplayRows * 48 + 'px'
  }
})
const list = defineModel<any>('list', { required: true })
const isDisable = computed(() => list.value.length >= 20)
const handleDelete = async (index: number) => {
  list.value.splice(index, 1)
  await nextTick()
  await formRefs.value?.forEach((formInstance) => formInstance.validate())
}
// 新增一项空数据
function append() {
  if (isDisable.value) return
  const obj = {
    suffix: '',
    cache_time: 1,
    cache_unit: 'd'
  }
  list.value.push(obj)
}

// 表单验证，外部保存时可调用验证数据有效性
async function validateFn() {
  if (!formRefs.value || !props.validate) {
    return
  }
  const res = await Promise.all(formRefs.value.map((item) => item.validate()))
  return res.every((item: any) => item === undefined)
}

watch(
  () => props.validate,
  (val) => {
    if (val) {
      return
    }
    nextTick(() => {
      formRefs.value?.forEach((formInstance) => {
        formInstance.clearValidate()
      })
    })
  }
)

defineExpose({ validateFn })
</script>
<style scoped lang="less">
.cache-rule {
  @apply rounded overflow-hidden rounded-2;
  width: var(--width);
  border: 1px solid var(---color-border-3, #dfe2e5);
  &__top {
    @apply flex items-center py-2  h-12  text-sm/22px text-3  font-semibold;
    border-bottom: 1px solid var(---color-border-3, #dfe2e5);
    background: var(---color-fill-1, #f8f9fa);
    div {
      @apply px-4;
    }
  }
  &__body {
    @apply flex flex-col max-h-60 overflow-auto;
    :deep(.rule-list) {
      @apply py-2 !flex h-12 !flex-row;
      &:not(:last-child) {
        border-bottom: 1px solid #f3f4f7;
      }
      .item {
        @apply px-4;
      }
      .arco-form-item-layout-vertical > .arco-form-item-label-col {
        @apply !mb-0;
      }
    }
  }
  &__footer {
    @apply flex-center  h-12 leading-12 text-primary cursor-pointer;
    border-top: 1px solid #f3f4f7;
    .disable-btn {
      @apply !text-#94BFFF cursor-not-allowed;
    }
  }
  &-item {
    &:last-child {
      .a-form-item {
        @apply mb-0;
      }
    }
  }
}
</style>
